/*
 * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://mindorks.com/license/apache-v2
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package org.changs.game.android;


import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.support.multidex.MultiDex;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.interceptors.HttpLoggingInterceptor;
import com.blankj.utilcode.util.Utils;

import org.changs.game.android.data.DataManager;
import org.changs.game.android.di.component.ApplicationComponent;
import org.changs.game.android.di.component.DaggerApplicationComponent;
import org.changs.game.android.di.module.ApplicationModule;
import org.changs.game.android.utils.AppLogger;

import javax.inject.Inject;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

public class MvpApp extends Application {

    @Inject DataManager mDataManager;
    @Inject CalligraphyConfig mCalligraphyConfig;

    private volatile boolean needToInject = true;
    private ApplicationComponent mApplicationComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        AppLogger.init();
        Utils.init(this);
        AndroidNetworking.initialize(getApplicationContext());
        if (BuildConfig.DEBUG) {
            AndroidNetworking.enableLogging(HttpLoggingInterceptor.Level.BASIC);
        }

        boolean canWrite = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                && Environment.getExternalStorageDirectory().canWrite();
        if (canWrite) injectIfNecessary();
    }

    public void injectIfNecessary() {
        if (needToInject) {
            synchronized (this) {
                if (needToInject) {
                    mApplicationComponent = DaggerApplicationComponent.builder()
                            .applicationModule(new ApplicationModule(this)).build();
                    mApplicationComponent.inject(this);
                    CalligraphyConfig.initDefault(mCalligraphyConfig);
                    needToInject = false;
                }
            }
        }
    }


    public ApplicationComponent getComponent() {
        return mApplicationComponent;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
